//注册和登录的盒子都是通过定位实现的
//注册在前.登录在后.所有登录压住注册的盒子
//需求1:点击里面的a链接,让对应的盒子显示隐藏

//步骤1:获取元素
let a1 = document.querySelector(".register a");
let a2 = document.querySelector(".login a");
let register = document.querySelector(".register");
let login = document.querySelector(".login");
//步骤2:注册点击事件
a1.onclick = function () {
  register.style.display = "none";
  login.style.display = "block";
};
a2.onclick = function () {
  login.style.display = "none";
  register.style.display = "block";
};

//步骤3:注册页面效验
//获取元素
let input1 = document.querySelector(".register [name=username]");
let input2 = document.querySelector(".register [name=password]");
let input3 = document.querySelector(".login [name=username]");
let input4 = document.querySelector(".login [name=password]");

//调用
ver(
  input1,
  "用户名不能为空",
  /^[\S]{2,15}$/,
  "用户名长度不能小于2位或超过15位"
);
ver(input2, "密码不能为空", /^[\S]{6,15}$/, "密码长度不能小于6位或超过15位");
ver(
  input3,
  "用户名不能为空",
  /^[\S]{2,15}$/,
  "用户名长度不能小于2位或超过15位"
);
ver(input4, "密码不能为空", /^[\S]{6,15}$/, "密码长度不能小于6位或超过15位");
//注册点击事件

//封装
function ver(ele, txt1, reg, txt2) {
  ele.oninput = function () {
    //非空校验
    if (this.value.trim() == "") {
      this.nextElementSibling.style.display = "block";
      this.nextElementSibling.innerHTML = txt1;
      return;
    } else {
      this.nextElementSibling.style.display = "none";
      this.nextElementSibling.innerHTML = "";
    }
    //长度校验
    if (reg.test(this.value.trim())) {
      //效验成功
      this.nextElementSibling.style.display = "none";
      this.nextElementSibling.innerHTML = "";
    } else {
      //效验不成功
      this.nextElementSibling.style.display = "block";
      this.nextElementSibling.innerHTML = txt2;
    }
  };
}

//注册
let registerForm = document.querySelector(".register form");
//点击事件
registerForm.addEventListener("submit", function (e) {
  //阻止表单默认跳转
  e.preventDefault();
  //发送axios请求
  axios({
    url: "/api/register",
    method: "post",
    data: $(this).serialize(),
    //params: { 'get请求参数'}
  }).then(({ data: res }) => {
    //成功回调
    //console.log(res);
    //校验
    if (res.code == 0) {
      toastr.success("恭喜注册成功");
      //如果成功就跳转登录页面
      a1.click();
      //重置表单
      registerForm.reset();
    }
  });
});

//登录
let loginForm = document.querySelector(".login form");
loginForm.addEventListener("submit", function (e) {
  //阻止表单默认跳转
  e.preventDefault();
  //发送axios请求
  axios({
    url: "/api/login",
    method: "post",
    data: $(this).serialize(loginForm),
    // params: { 'get请求参数'}
  }).then(({ data: res }) => {
    //成功回调
    // console.log(res);
    //判断成功的处理情况
    if (res.code == 0) {
      //登录成功给提示框
      toastr.success("登录成功");
      //跳转首页
      location.href = "./index.html";
      //保存token
      localStorage.setItem("myToken", res.token);
    }
  });
});
